import React, { useEffect, useState } from "react";
import axios from "axios";
import { Table, message, Input, Button, Modal } from "antd";
import { debounce } from "lodash";
const Index = () => {
  const [list, setList] = useState([]);
  const [ids, setIds] = useState<React.Key[]>([]);
  const columns = [
    {
      key: "id",
      dataIndex: "id",
      title: "id",
    },
    {
      key: "name",
      dataIndex: "name",
      title: "name",
    },
    {
      key: "price",
      dataIndex: "price",
      title: "price",
    },
    {
      key: "address",
      dataIndex: "address",
      title: "address",
    },
    {
      key: "tel",
      dataIndex: "tel",
      title: "tel",
    },
    {
      key: "check",
      title: "操作",
      render(_: any) {
        return (
          <div>
            <button onClick={() => handleCheck(_.id)}>审核</button>;
            <button onClick={() => handleDelete(_.id)}>删除</button>;
          </div>
        );
      },
    },
  ];

  const fetchList = async (value?: string) => {
    const resp = await axios.get("/api/person/check", { params: { value } });
    setList(resp.data.data);
  };

  const fetchListDebounce = debounce(fetchList, 1000);

  const handleCheck = async (id: string) => {
    const resp = await axios.get("/api/person/check/" + id);
    message.success("审核成功");
    fetchList();
  };

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: "确认删除吗",
      async onOk() {
        const resp = await axios.get("/api/person/check/delete", {
          params: { id },
        });
        message.success("删除成功");
        fetchList();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const handleCheckAll = () => {
    ids.forEach(async (id) => {
      const resp = await axios.get("/api/person/check/" + id);
    });
    message.success("批量审核成功");
    fetchList();
  };

  useEffect(() => {
    fetchList();
  }, []);
	
  return (
    <div>
      <Input.Search
        onChange={(e) => fetchListDebounce(e.target.value)}
      ></Input.Search>

      <Button onClick={() => handleCheckAll()}>批量删除</Button>

      <Table
        columns={columns}
        dataSource={list}
        rowKey={"id"}
        rowSelection={{
          onChange(keys: React.Key[]) {
            setIds(keys);
          },
        }}
      ></Table>
    </div>
  );
};

export default Index;
